﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace XiangziProjectTemplete.Core.Controllers
{
    /// <summary>
    /// Excel管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize] //先暂时去掉验证
    public class ExcelController : Controller
    {
        private IWebHostEnvironment _environment;//将IWebHostEnvironment注入到Controller中，并分配给私有属性Environment，随后用于获取WebRootPath和ContentRootPath。
        /// <summary>
        /// 构造函数
        /// </summary>
        ///  <param name="environment"></param>
        public ExcelController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        /// <summary>
        /// Form表单之单文件上传
        /// </summary>
        /// <param name="file">form表单文件流信息</param>
        /// <param name="categroy">分类</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> FormSingleFileUpload(IFormFile file, string categroy)
        {
            var data = new MessageModel<string>();
            try
            {
                data = await this.D_FormSingleFileUpload(file);
                if (!data.success)
                {
                    return data;
                }
                var webRootPath = _environment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") 
                Dictionary<string, string> cellheader = new Dictionary<string, string>();
                switch (categroy)
                {
                    case "CoilSalver"://线圈托盘
                                      //读取并验证
                        cellheader = new Dictionary<string, string> {
                    { "ceshijiaoben", "测试脚本" },
                    { "sysCode", "集成系统" },
                    { "fenlei", "分类" }
                };
                        break;
                    case "test":
                        break;
                    default:
                        data.success = false;
                        data.msg = "分类不正确";
                        return data;
                }

                //验证数据
                StringBuilder errorMsg = new StringBuilder();
                List<FileTest> enlist = ExcelHelper.ExcelToEntityListForInitCodeItems<FileTest>(cellheader, webRootPath + data.response, out errorMsg);
                if (!string.IsNullOrEmpty(errorMsg.ToString()))
                {
                    data.msg = "错误:" + errorMsg.ToString();
                    return data;
                }

                data = new MessageModel<string>()
                {
                    response = "",
                    msg = "上传成功",
                    success = true,
                };
                return data;
            }
            catch (Exception ex)
            {
                data.msg = "出现异常，异常信息为：" + ex.Message;
                return data;
            }
        }

        /// <summary>
        /// Form表单之单文件上传
        /// </summary>
        /// <param name="formFile">form表单文件流信息</param>
        /// <returns></returns>
        private async Task<MessageModel<string>> D_FormSingleFileUpload(IFormFile file)
        {
            var data = new MessageModel<string>();
            var currentDate = DateTime.Now;
            var webRootPath = _environment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") 

            try
            {
                var filePath = $"/UploadFile/";

                //创建每日存储文件夹
                if (!Directory.Exists(webRootPath + filePath))
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }

                #region 移除之前的文档
                int removeDays = 5;//30
                string removePath = webRootPath + filePath;
                FileHelper.DeleteOldFiles(removePath, removeDays);
                #endregion

                if (file != null)
                {
                    //文件后缀
                    var fileExtension = Path.GetExtension(file.FileName);//获取文件格式，拓展名

                    //判断文件大小
                    var fileSize = file.Length;

                    if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                    {
                        data.msg = "上传的文件不能大于10M";
                        return data;
                    }

                    //保存的文件名称(以名称和保存时间命名)
                    var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                    //文件保存
                    using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }

                    //完整的文件路径
                    var completeFilePath = Path.Combine(filePath, saveName);

                    data = new MessageModel<string>()
                    {
                        response = completeFilePath,
                        msg = "上传成功",
                        success = true,
                    };
                    return data;
                }
                else
                {
                    data.msg = "上传失败，未检测上传的文件信息";
                    return data;
                }
            }
            catch (Exception ex)
            {
                data.msg = "文件保存失败，异常信息为：" + ex.Message;
                return data;
            }
        }


        /// <summary>
        /// 下载Excel模板文件
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public FileStreamResult DownExcelTemplete([FromServices] IWebHostEnvironment environment, string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return null;
            }
            // 前端 blob 接收，具体查看前端admin代码
            string filepath = Path.Combine(environment.WebRootPath + "/FileTemplate", filename);
            var stream = System.IO.File.OpenRead(filepath);
            //string fileExt = ".bmd";
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            //var memi = provider.Mappings[fileExt];
            var fileName = Path.GetFileName(filepath);

            HttpContext.Response.Headers.Add("fileName", fileName);

            return File(stream, "application/octet-stream", fileName);
        }
    }
}

